import json
import time

import jwt
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib import auth
from django.http import HttpResponse, JsonResponse

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from django.middleware.csrf import get_token
from jwt import PyJWTError


@csrf_exempt
def register(request):
    if request.method == 'POST':
        body = json.loads(request.body)

        username = body["username"]
        password = body["password"]
        email = body["email"]

        if len(User.objects.filter(username=username)) != 0:
            return HttpResponse(status=201, content="用户名已存在")

        try:
            res = User.objects.create_user(username=username, password=password, email=email)
            return HttpResponse()
        except BaseException:
            return HttpResponse(status=201)


@csrf_exempt
def login(request):
    if request.method == 'POST':
        body = json.loads(request.body)

        username = body["username"]
        password = body["password"]

        print("login:")
        if len(User.objects.filter(username=username)) == 0:
            return HttpResponse(status=201, content="用户名不存在")
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            token = jwt.encode({'username': username, 'id': user.id,
                                'exp':time.time()+60*60}, '79846517984651ryvgubhnj',
                               algorithm='HS256')
            return HttpResponse(token)
        else:
            return HttpResponse(status=201, content="用户名或密码错误")


def check(request):
    if request.method == 'GET':
        try:
            token = request.GET.get("token")
            user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
        except PyJWTError:
            return HttpResponse(status=402, content="请重新登录")
        return HttpResponse()
